
global data_folder "W:\intimate\data"
global log_folder "W:\intimate\dofiles\logs"
global result_folder "W:\intimate\results"

local go_back = 17

local var_list sphnro

foreach y of numlist 2005/2015 { // for matching so just need for subset of years

		use shnro `var_list' sukup using "D:\ready-made\FLEED_TOTAL\2016\fleed_kokonais_`y'.dta", clear
		keep if sukup=="2" //keep only female
		
		
		// rename to wide format
		foreach thing in `var_list'{
			ren `thing' `thing'0 // year get together
		}
		g info_missing0 = 0
		
		
		forvalues j = 1/`go_back' {
			
			local y_1 = `y'-`j'
			
		
			
			merge 1:1 shnro using "D:\ready-made\FLEED_TOTAL\2016\fleed_kokonais_`y_1'.dta", ///
				keepusing( `var_list')
			drop if _merge==2
			
	
			
			foreach thing in `var_list' {
				ren `thing' `thing'`j'
			}
			g info_missing`j' = (_merge==1)
			drop _merge
			
		}
		
		gen year=`y'
		
		save "$data_folder\relationship_history_`y'.dta", replace
}

// reshape 


foreach y of numlist 2005/2015 {
use "$data_folder\relationship_history_`y'.dta", clear 
drop info* sukup
rename year year_event 
reshape long sphnro, i(shnro  year_event) j(time)

gen spouse=(sphnro!="")

sort shnro year_event time
bys shnro year_event: egen relation_duration=total(spouse)


egen tag=tag(shnro year_event sphnro)
egen ndistinct=total(tag), by(shnro year_event)

keep if time==0 

keep shnro year_event relation_duration ndistinct 

gen avg_relation_year=0 if relation_duration==0
replace avg_relation_year=relation_duration/ndistinct if ndistinct!=0
save "$data_folder\relationship_hist_`y'.dta", replace
}



clear
forvalues y=2005/2015{
	append using "$data_folder\relationship_hist_`y'.dta"
	
}


save "$data_folder\relationship_hist_allyears.dta", replace 

